/*
 * @lc app=leetcode.cn id=394 lang=javascript
 *
 * [394] 字符串解码
 */

// @lc code=start
/**
 * @param {string} s
 * @return {string}
 */
var decodeString = function (s) {
  if (!s.includes("[")) return s;
  let arr = [];
  for (let i = 0; i < s.length; i++) {
    if (s[i] == "[") {
      arr.push(i);
    }
    if (s[i] == "]") {
      let start = arr.pop();
      let end = i;
      if (arr.length == 0) {
        let num = /\d+/.exec(s.slice(0, start));
        let len = (num + "").length;
        return (
          s.slice(0, start - len) +
          decodeString(s.slice(start + 1, end)).repeat(num ? num : 0) +
          decodeString(s.slice(end + 1, s.length))
        );
      }
    }
  }
};
// @lc code=end

decodeString("3[a]2[bc]");
